package com.huangyi.order.service;

import com.huangyi.order.mapper.OrderMapper;
import com.huangyi.order.model.OrderInfo;
import com.huangyi.order.model.ProductInfo;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    public List<ServiceInstance> instances;
    //@PostConstruct
//    public void init(){
//        instances = discoveryClient.getInstances("product-service");
//    }
    @PostConstruct
    public List<ServiceInstance>  init(){
        instances = discoveryClient.getInstances("product-service");
        return instances;
    }
    public AtomicInteger count = new AtomicInteger(1);


//    public OrderInfo selectOrderById(Integer id) {
//        OrderInfo orderInfo = orderMapper.selectOrderById(id);
//
//        Integer index = count.getAndIncrement() % instances.size();
////        String url = "http://127.0.0.1:9090/product/" + orderInfo.getProductId();
//        //获取 product-server 不加任何 RequesMapping 的 url
//        String getUri = instances.get(index).getUri().toString();
//        String getUrl = getUri + "/product/" + orderInfo.getProductId();
//
//        log.info("调取 url：" + getUrl);
//        ProductInfo productInfo = restTemplate.getForObject(getUrl, ProductInfo.class);
//        orderInfo.setProductInfo(productInfo);
//        return orderInfo;
//    }
public OrderInfo selectOrderById(Integer id) {
    OrderInfo orderInfo = orderMapper.selectOrderById(id);
    String url = "http://product-service/product/" + orderInfo.getProductId();
    log.info("调取 url：" + url );
    ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
    orderInfo.setProductInfo(productInfo);
    return orderInfo;
}
}
